/**
 * @author haixuanwo
 * @email haixuanwo_clark@hotmail.com
 * @date 2021-03-23
 * @brief sqlite3数据库类
 */

#include <stdio.h>
#include "mysqlite.h"

int mySqlite::callback(void *data, int argc, char **argv, char **azColName)
{
    if (nullptr != data)
    {
        for (int i = 0; i < argc; i++)
        {
            *((int *)data) = atoi(argv[i]);
        }
    }
    return 0;
}

mySqlite::mySqlite(const char *db_name)
{
    db = NULL;
    int rc = sqlite3_open(db_name, &db);
    if (rc)
    {
        fprintf(stderr, "can't open database:%s\n", sqlite3_errmsg(db));
    }
}

bool mySqlite::exec_sql_cmd(const char* cmd, void *data)
{
    char *zErrMsg = nullptr;

    if (NULL == db)
    {
        return false;
    }

    int rc = sqlite3_exec(db, cmd, callback, data, &zErrMsg);
    if (rc != SQLITE_OK)
    {
        fprintf(stderr, "SQL error: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
        return false;
    }

    return true;
}

bool mySqlite::sql_select(const char* cmd, std::string &tableData)
{
    char *zErrMsg = nullptr;
    char **table = NULL;
    int rows = 0;
    int columns = 0;
    int index = 0;

    tableData.erase(0, tableData.size() - 1);

    int rc = sqlite3_get_table(db, cmd, &table, &rows, &columns, &zErrMsg);
    if( rc!=SQLITE_OK )
    {
        fprintf(stderr, "SQL error: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
        return false;
    }

    if(rows || columns)
	{
		for(int i = 0; i < rows+1; i++)
		{
			int iflag = 0;
			for(int j = 0; j < columns; j++)
			{
				tableData += table[index++];
				iflag++;

				if(iflag == columns)
					tableData += ";";
				else
					tableData += ",";
			}
		}
	}

    sqlite3_free_table(table);
    return true;
}

mySqlite::~mySqlite()
{
    if (NULL != db)
        sqlite3_close(db);
}

